const canvas = document.querySelector("#Animation");
const gd = canvas.getContext('2d');
var timer = null,
	ball = {
		x : 0,
		y : 0,
		r : 2,
		vx : 0,
		vy : 0,
		color : null
	}, mouse= {
		x : undefined,
		y : undefined
	}, balls = [],
	colors = [ 'red', 'orange', 'yellow', 'green', 'rgb( 0, 127.5, 255 ), blue, purple' ],
	r = 0,
	g = 0,
	b = 0,
	vr = 1,
	vg = 1,
	vb = 1;

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

const getRandom = ( min, max ) => {
	return Math.floor( Math.random() * ( max - min ) ) + 1;
}

const getRandomVector = ( min, max ) => {
	const num = ( Math.floor( Math.random() * ( max - min ) ) + 1 ) * ( Math.random() / 2 - Math.random() );
	if( num === 0 ) return getRandomVector();
	return num;
}

const getLength = ( obj1, obj2 ) => {
	return Math.sqrt( ( obj1.x - obj2.x ) * ( obj1.x - obj2.x ) + ( obj1.y - obj2.y ) * ( obj1.y - obj2.y ) );
}

const drawLine = ( p1, p2, width ) => {
	gd.beginPath();
	gd.strokeStyle = 'rgb( ' + r + ', ' + g + ', ' + b + ' )';
	gd.moveTo( p1.x, p1.y );
	gd.lineTo( p2.x, p2.y );
	gd.lineWidth = width / getLength( p1, p2 );
	gd.stroke();
}

r = getRandom( 0, 255 )
g = getRandom( 0, 255 )
b = getRandom( 0, 255 )

for( let i = 0 ; i < 150 ; i ++ ){
	ball.x = getRandom( ball.r, canvas.width - ball.r );
	ball.y = getRandom( ball.r, canvas.height - ball.r );
	ball.vx = getRandomVector( -2, 2 );
	ball.vy = getRandomVector( -2, 2 );
	ball.color = colors[ Math.floor( Math.random() * colors.length ) ];
	balls.push( { ... ball } );
}

canvas.onmousemove = function( e ){
	mouse.x = e.pageX;
	mouse.y = e.pageY;
}

window.onload = function(){
	clearInterval( timer );
	timer = setInterval( function(){
		draw();
		update();
	}, 10 );
}

function draw(){
	gd.clearRect( 0, 0, canvas.width, canvas.height );
	for( let i = 0 ; i < balls.length ; i ++ ){
		gd.beginPath();
		gd.fillStyle = balls[i].color;
		gd.arc( balls[i].x, balls[i].y, balls[i].r, 0, Math.PI * 2 );
		gd.fill();
		for( let j = 0 ; j < balls.length ; j ++ ){
			if( getLength( balls[i], balls[j] ) < canvas.width / 15 ){
				drawLine( balls[i], balls[j], canvas.width / 15 );
			}
		}
		if( getLength( balls[i], mouse ) < canvas.width / 15 * 3 / 2 ){
			drawLine( balls[i], mouse, canvas.width / 15 * 3 / 2 );
		}
	}
}

function update(){
	for( let i = 0 ; i < balls.length ; i ++ ){
		balls[i].x += balls[i].vx;
		balls[i].y += balls[i].vy;
		if( balls[i].x < balls[i].r || balls[i].x > canvas.width - balls[i].r ) balls[i].vx = -balls[i].vx;
		if( balls[i].y < balls[i].r || balls[i].y > canvas.height - balls[i].r ) balls[i].vy = -balls[i].vy;
	}
	r += vr;
	g += vg;
	b += vb;
	if( r >= 255 ) vr = -vr;
	if( g >= 255 ) vg = -vg;
	if( b >= 255 ) vb = -vb;
}